import Vue from 'vue'
import Router from 'vue-router'
import { concatRoute } from '@/utils/helper/route.js'

Vue.use(Router)

/* Router Modules */
import pluginRouter from './modules/plugin.js'
import systemRouter from './modules/system'

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  {
    path: '/',
    component: () => import("@/layout/index.vue"),
    redirect: '/dashboard',
    meta: {},
    children: [
      {
        path: '/dashboard',
        component: () => import('../views/home/index.vue'),
        name: 'Dashboard',
        meta: {
          title: '首页',
          icon: 'chart',
          affix: true
        }
      }
    ]
  },
]

// 菜单
export const menusList = concatRoute([pluginRouter, systemRouter])

const routesList = menusList
/**
 * asyncRoutes
 */
export const asyncRoutes = [
  ...routesList,
  // 404 页面必须放在最后 !!!
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({
      y: 0
    }),
    routes: [...constantRoutes, ...asyncRoutes]
  })

const router = createRouter()

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

//添加全局路由守卫，用来判断页面前进或是后退
router.beforeEach((to, from, next) => {
  if (typeof to.meta.keepAlive !== 'undefined') {
    const toDepth = to.path.split("/").length;
    const fromDepth = from.path.split("/").length;
    to.query.isBack = toDepth < fromDepth
  }
  next();
});

export default router
